/**
 * 微信授权认证服务
 * 参考 index.vue 实现简单的微信授权认证
 */

class AuthService {
    constructor() {
        this.isInitialized = false;
        this.userInfo = null;
    }

    /**
     * 初始化认证服务 - 参考 index.vue 的实现
     */
    async init() {
        try {
            console.log('🔐 初始化认证服务...');
            
            // 检查本地存储的认证信息
            const storedUserId = uni.getStorageSync('userid');
            const storedNickname = uni.getStorageSync('nickname');
            
            if (storedUserId && storedNickname) {
                this.userInfo = {
                    userid: storedUserId,
                    nickname: storedNickname
                };
                console.log('🔐 发现本地认证信息:', this.userInfo);
                this.isInitialized = true;
                return { success: true, userInfo: this.userInfo };
            }
            
            // H5环境：检查URL中的参数
            const urlParams = new URLSearchParams(window.location.search);
            const userid = urlParams.get('userid');
            const name = urlParams.get('name');
            const code = urlParams.get('code');
            
            // 情况1：URL中有用户信息（来自后端Login重定向）
            if (userid && name) {
                console.log('🔐 H5环境：检测到URL中的用户信息，保存到本地存储:', { userid, name });
                
                // 保存用户信息到本地存储
                uni.setStorageSync("userid", userid);
                uni.setStorageSync("nickname", name);
                
                this.userInfo = {
                    userid: userid,
                    nickname: name
                };
                this.isInitialized = true;
                
                // 清理URL参数（可选）
                const cleanUrl = window.location.origin + window.location.pathname + window.location.hash;
                window.history.replaceState({}, document.title, cleanUrl);
                
                return { success: true, userInfo: this.userInfo };
            }
            
            // 情况2：URL中有微信授权码，需要调用后端接口获取用户信息
            if (code) {
                console.log('🔐 H5环境：检测到微信授权码，调用后端接口获取用户信息:', code);
                return await this.handleWeChatCode(code);
            }
            
            // 情况3：没有任何有用的参数，需要跳转到微信授权页面
            console.log('🔐 H5环境：无用户信息和授权码，需要跳转到微信授权页面');
            return { success: false, error: '需要微信授权', needRedirect: true };
            
        } catch (error) {
            console.error('🔐 认证服务初始化失败:', error);
            return { success: false, error: error.message || error };
        }
    }

    /**
     * 处理微信授权码，调用后端接口获取用户信息
     */
    async handleWeChatCode(code) {
        console.log('🔐 开始处理微信授权码:', code);
        
        return new Promise((resolve) => {
            // 从 store 获取当前环境的API地址
            const store = require('@/store/index.js').default;
            const baseUrl = store.getters.currentApiBaseUrl;
            const apiUrl = `${baseUrl}/${store.state.apiVersion}/url?code=${code}`;
            
            console.log('🔐 调用后端Url接口:', apiUrl);
            
            uni.request({
                url: apiUrl,
                method: 'GET',
                success: (res) => {
                    console.log('🔐 后端返回完整响应:', res);
                    console.log('🔐 后端返回数据:', res.data);
                    
                    if (res.data && res.data.Status == 1) {
                        console.log('🔐 认证成功:', res.data.Data);
                        
                        try {
                            // 保存用户信息到本地存储
                            uni.setStorageSync("userid", res.data.Data.userid);
                            uni.setStorageSync("nickname", res.data.Data.nickname);
                            
                            this.userInfo = {
                                userid: res.data.Data.userid,
                                nickname: res.data.Data.nickname
                            };
                            this.isInitialized = true;
                            
                            // 清理URL参数
                            const cleanUrl = window.location.origin + window.location.pathname + window.location.hash;
                            window.history.replaceState({}, document.title, cleanUrl);
                            
                            resolve({ success: true, userInfo: this.userInfo });
                        } catch (e) {
                            console.error('🔐 保存用户信息失败:', e);
                            resolve({ success: false, error: '保存用户信息失败' });
                        }
                    } else {
                        console.error('🔐 认证失败:', res.data);
                        resolve({ 
                            success: false, 
                            error: '认证失败', 
                            details: res.data,
                            code: code
                        });
                    }
                },
                fail: (err) => {
                    console.error('🔐 网络请求失败:', err);
                    resolve({ 
                        success: false, 
                        error: '网络请求失败', 
                        details: err,
                        code: code
                    });
                }
            });
        });
    }

    // 只支持H5环境，小程序环境已移除

    /**
     * 强制重新认证 - 清除本地存储并重新登录
     */
    async forceReAuth() {
        console.log('🔐 强制重新认证...');
        
        // 清除本地存储
        uni.clearStorageSync();
        this.userInfo = null;
        this.isInitialized = false;
        
        // 重新执行微信登录
        return await this.performWeChatLogin();
    }

    /**
     * 检查认证状态
     */
    isAuthenticated() {
        return this.isInitialized && this.userInfo && this.userInfo.userid;
    }

    /**
     * 获取用户信息
     */
    getUserInfo() {
        return this.userInfo;
    }

    /**
     * 获取用户ID
     */
    getUserId() {
        return this.userInfo ? this.userInfo.userid : null;
    }

    /**
     * 登出
     */
    logout() {
        console.log('🔐 用户登出');
        this.userInfo = null;
        this.isInitialized = false;
        
        // 清除本地存储
        uni.removeStorageSync('userid');
        uni.removeStorageSync('nickname');
        
        // 跳转到首页重新认证
        uni.reLaunch({
            url: '/pages/dtest/home'
        });
    }
}

// 创建全局认证服务实例
const authService = new AuthService();

// 导出认证服务
export default authService;

// 导出简化的认证检查函数
export const checkAuth = async (options = { autoRedirect: false }) => {
    console.log('🔐 检查认证状态...');
    
    // 如果已经认证过，直接返回
    if (authService.isAuthenticated()) {
        return { success: true, userInfo: authService.getUserInfo() };
    }
    
    // 否则执行认证初始化
    const authResult = await authService.init();
    
    if (!authResult.success) {
        console.error('🔐 认证失败:', authResult.error);
        
        // 构建详细的错误信息
        const detailedError = {
            success: false,
            error: authResult.error,
            needRedirect: authResult.needRedirect,
            currentUrl: window.location.href,
            urlParams: Object.fromEntries(new URLSearchParams(window.location.search)),
            localStorage: {
                userid: uni.getStorageSync('userid'),
                nickname: uni.getStorageSync('nickname')
            }
        };
        
        // 如果需要重定向且调用者明确要求自动跳转
        if ((authResult.needRedirect || authResult.error === '需要微信授权') && options.autoRedirect) {
            console.log('🔐 H5环境：跳转到微信授权页面');
            
            // 从 store 获取当前环境的API地址
            const store = require('@/store/index.js').default;
            const baseUrl = store.getters.currentApiBaseUrl;
            
            // 构建微信授权回调URL（必须使用可信域名）
            const backendLoginUrl = `${store.state.wechatAuthDomain}/${store.state.apiVersion}/login`;
            const redirectUri = encodeURIComponent(backendLoginUrl);
            
            // 构建微信授权URL
            const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=ww44da95994e8f32c1&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_base&state=STATE&agentid=1000196#wechat_redirect`;
            
            // 添加授权URL到错误信息中
            detailedError.authUrl = authUrl;
            detailedError.backendLoginUrl = backendLoginUrl;
            
            console.log('🔐 跳转到授权URL:', authUrl);
            console.log('🔐 redirect_uri:', backendLoginUrl);
            
            window.location.href = authUrl;
            
            return { success: false, error: '跳转微信授权' };
        }
        
        // 默认不自动跳转，返回详细错误信息供调用者查看
        if (authResult.needRedirect || authResult.error === '需要微信授权') {
            // 构建授权URL但不跳转
            const store = require('@/store/index.js').default;
            const baseUrl = store.getters.currentApiBaseUrl;
            const backendLoginUrl = `${store.state.wechatAuthDomain}/${store.state.apiVersion}/login`;
            const redirectUri = encodeURIComponent(backendLoginUrl);
            const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=ww44da95994e8f32c1&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_base&state=STATE&agentid=1000196#wechat_redirect`;
            
            detailedError.authUrl = authUrl;
            detailedError.backendLoginUrl = backendLoginUrl;
            
            console.log('🔐 认证失败详细信息:', detailedError);
        }
        
        return detailedError;
    }
    
    return authResult;
};

// 导出手动跳转授权的函数
export const redirectToAuth = () => {
    const store = require('@/store/index.js').default;
    
    // 🚨 修复：redirect_uri 应该指向前端域名，不是后端API
    const frontendDomain = store.state.wechatAuthDomain; // 前端域名
    const redirectUri = encodeURIComponent(`${frontendDomain}/#/`);
    const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=ww44da95994e8f32c1&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_base&state=STATE&agentid=1000196#wechat_redirect`;
    
    console.log('🔐 手动跳转到微信授权:', authUrl);
    console.log('🔐 redirect_uri:', `${frontendDomain}/#/`);
    window.location.href = authUrl;
};
